/*********************************************************************************
    This software is created under the term GNU General Public License.
    You should have received a copy of the GNU General Public License.
    If not, write to the Free Software Foundation, 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

heap:
    a pool of memory. see the comment below

author: xiangyun.kong(lo-sor@hotmail.com)
create: 2-26-2011

changes:

**********************************************************************************/
#ifndef __clib_heap_h__
#define __clib_heap_h__

#include <inttype.h>

// a heap node is a large piece of memory whose beginning is
// reserved part which for struct _heap_node. the rest of the memory
// is used for user( the value returned from alloc or realloc ).
// the following photo may help you to understand the structure:
//
//            part I                        part II
//  |pre,nxt,dpre,dnxt,size,free|.......return for user.......|
//
// if a heap's part II is larger than user required, we separate
// the heap into two pieces of smaller heaps. we may call these two
// are brothers.and  we use dpre and dnxt to link the two pieces. 
// through dpre and dnxt, when the two pieces are all freed from
// user, we can make them together again
typedef struct _heap_node
{
    // point to the valid heaps in the heap pool
    struct _heap_node *pre, *nxt;
    // point to its brothers,if any. a brother is a heap who was
    // separated from the same large heap with "this" heap
    struct _heap_node *dpre, *dnxt;
    // heap size, in byte, include head(part I) and data(part II)
    uint32 size;
    // mark if the heap was allocated
    int free;
} hp_node;

// a heap pool. we make some larger heap at the beginning of the
// heap chain, but not strict.
typedef struct _heap
{
    // begin and end is the two head of a list whose content is heap
    hp_node *begin;
    hp_node *end;

    // the original memory we allocated from system.
    int32 iblk;
    void **blk;
} heap;

// create a new heap pool
heap* hp_create( );
// release a heap pool
void hp_release( heap *_hp );
// alloc memory from heap pool
void* hp_alloc( heap *_hp, uint32 _sz );
// free memory to heap pool
void hp_free( heap *_hp, void *_data );
// get the memory size which allocated from hp_alloc
uint32 hp_size( void *_data );

#endif // __clib_heap_h__
